package synchronicity.ui;

import java.util.Date;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.DateField;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;

import synchronicity.util.MeetingScheduler;
import ui.DisplayContext;
import ui.Screen;

public class ScheduleMeetingScreen extends Screen {
	private static ScheduleMeetingScreen instance;

	private Form container;

	private DateField startDate, endDate;

	private TextField length;

	private TextField title;

	private ScheduleMeetingScreen(DisplayContext context) {
		super(context);
		container = new Form("Setup Meeting");
		startDate = new DateField("Time range start", DateField.DATE);
		endDate = new DateField("Time range end", DateField.DATE);
		length = new TextField("Meeting length", "", 3, TextField.NUMERIC);
		title = new TextField("Meeting title", "", 20, TextField.ANY);
		container.append(startDate);
		container.append(endDate);
		container.append(length);
		container.append(title);
	}

	public static synchronized ScheduleMeetingScreen getInstance(
			DisplayContext context) {
		if (instance == null) {
			instance = new ScheduleMeetingScreen(context);
		}
		return instance;
	}

	protected Command[] getCommands() {
		return getDefaultCommands();
	}

	protected Displayable getDisplayable() {
		return container;
	}

	protected String getTitle() {
		return "Synchronicity";
	}

	public void commandAction(Command command, Displayable display) {
		if (command.getCommandType() == Command.CANCEL) {
			switchScreen(HomeScreen.getInstance(getContext()));
		} else {
			final Date start = startDate.getDate();
			// make the end inclusive
			final Date end = new Date(endDate.getDate().getTime() + 1000 * 60 * 60 * 24);
			// Length is given in minutes and needs to be converted to ms
			long length = Long.parseLong(this.length.getString());
			length = length * 60 * 1000;

			MeetingScheduler scheduler = new MeetingScheduler(start,
					end, length, title.getString(),
					getContext().getHost());
			// This will _all_ run asynchronously (but in the right order since
			// worker is single threaded)
			worker.runCode(scheduler);
			//switchScreen(new ScheduleResultScreen(scheduler.getMeetingResult(),getContext()));
		}
	}
}
